package com.trolls.client;

import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class LaTerreDesTrolls implements EntryPoint {
	
	private static LaTerreDesTrolls SINGLETON;
	private DockPanel dockpanel;
	private HorizontalPanel header ;
	private HorizontalPanel footer;
	private VerticalPanel menu;
	private Content content;
	private ArrayList<Item> items;
	private ArrayList<Item> listeRaces;
	private int numPage = 0;
	private AsyncCallback<ArrayList<Troll>> Trollcallback;
	private AsyncCallback<ArrayList<Race>> Racecallback;
	private AsyncCallback<ArrayList<Troll>> SaveTrollcallback;
	private AsyncCallback<ArrayList<Troll>> RemoveTrollcallback;
	
	public AsyncCallback<ArrayList<Troll>> getSaveTrollcallback() {
		return SaveTrollcallback;
	}

	public AsyncCallback<ArrayList<Troll>> getRemoveTrollcallback() {
		return RemoveTrollcallback;
	}
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	
	private final ServiceTrollAsync myServiceTroll = GWT
			.create(ServiceTroll.class);

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */

	public ServiceTrollAsync getMyServiceTroll() {
		return myServiceTroll;
	}
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		SINGLETON = this;
		dockpanel = new DockPanel();
		dockpanel.setSize("800px", "800px");
		dockpanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE);
		dockpanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		dockpanel.setWidth("90%");
		dockpanel.setHeight("90%");
		dockpanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		dockpanel.getElement().setId("pc-template-dockPanel");
		content = new Content();
		//-------------Header
		Label Titre = new Label("La Terre des Trolls");
		Titre.getElement().setId("pc-template-titre");
		header= new HorizontalPanel();
		header.add(Titre);
		//-------------
		//-------------Footer
		footer= new HorizontalPanel();
		footer.add(new Label("2012 - Moez Askri & Colin Fournier"));
		//-------------
		//-------------Menu
		menu= new VerticalPanel();
		MenuTroll menuBar = new MenuTroll(true);
		    // Make a command that we will execute from all leaves.
		Command cmdShowNew = new Command() {
		      public void execute() {
		        MenuTroll m = (MenuTroll)menu.getWidget(0);
		        m.getActiveItem().setStyleName("gwt-MenuItem");
		        m.getItem(0).setStyleName("gwt-MenuItem-active");
		        numPage = 1;
		        myServiceTroll.getRaces(Racecallback);

		      }
		  };
		  Command cmdShowEdit = new Command() {
		      public void execute() {
		        MenuTroll m = (MenuTroll)menu.getWidget(0);
		        m.getActiveItem().setStyleName("gwt-MenuItem");
		        m.getItem(1).setStyleName("gwt-MenuItem-active");
		        numPage = 2;
		        myServiceTroll.getTrolls(Trollcallback);
		      }
		  };
		  Command cmdShowList = new Command() {
		      public void execute() {
		        MenuTroll m = (MenuTroll)menu.getWidget(0);
		        m.getActiveItem().setStyleName("gwt-MenuItem");
		        m.getItem(2).setStyleName("gwt-MenuItem-active");
		        numPage = 3;
		        myServiceTroll.getTrolls(Trollcallback);

		      }
		  };
		  Command cmdShowTable = new Command() {
		      public void execute() {
		        MenuTroll m = (MenuTroll)menu.getWidget(0);
		        m.getActiveItem().setStyleName("gwt-MenuItem");
		        m.getItem(3).setStyleName("gwt-MenuItem-active");
		        numPage = 4;
		        myServiceTroll.getTrolls(Trollcallback);

		      }
		  };
		MenuItem menuItemFirst = new MenuItem("Créer un Troll", cmdShowNew);
		menuItemFirst.setStyleName("gwt-MenuItem-active");
		menuBar.addItem(menuItemFirst);
		menuBar.addItem("Modifier un Troll", cmdShowEdit);
		menuBar.addItem("La Taverne", cmdShowList);
		menuBar.addItem("TrombinoTroll", cmdShowTable);
		//menuBar.selectItem(menuItemFirst);
		menu.add(menuBar);

				//-------------
		dockpanel.add(header, DockPanel.NORTH);
		dockpanel.add(footer, DockPanel.SOUTH);
		dockpanel.add(menu, DockPanel.WEST);

		RootPanel.get().add(dockpanel);		
		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		// We can set the id of a widget by accessing its Element
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(serverResponseLabel);

		
		
		AsyncCallback<String> autreCallback = new AsyncCallback<String>() {
			public void onFailure(Throwable ex) {
				RootPanel.get().add(new HTML("oups : " + ex.toString()));
				// Show the RPC error message to the user
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(SERVER_ERROR);
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
			}
		};
		Racecallback = new AsyncCallback<ArrayList<Race>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				RootPanel.get().add(new HTML("oups : " + caught.toString()));
				// Show the RPC error message to the user
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(SERVER_ERROR);
			}

			public void onSuccess(ArrayList<Race> races) {
				// TODO Auto-generated method stub
				items = new ArrayList<Item>();
				for (Race item : races) {
					items.add(item);
				}
				showContent(items);
				listeRaces =  items;

			}

		};
		Trollcallback = new AsyncCallback<ArrayList<Troll>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				RootPanel.get().add(new HTML("oups : " + caught.toString()));
				// Show the RPC error message to the user
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(SERVER_ERROR);
			}

			@Override
			public void onSuccess(ArrayList<Troll> trolls) {
				// TODO Auto-generated method stub
				//ArrayList<Item> items = new ArrayList<Item>();
				items = new ArrayList<Item>();
				for (Troll item : trolls) {
					items.add(item);
				}
				showContent(items);
			}

		};
		SaveTrollcallback = new AsyncCallback<ArrayList<Troll>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				getContent().SetServeurInfo("La sauvegarde a échouée");
			}

			@Override
			public void onSuccess(ArrayList<Troll> trolls) {
				Item trollEnvoye = getContent().getItemEnCour();
				items = new ArrayList<Item>();
				for (Troll item : trolls) {
					if(item.getId()==trollEnvoye.getId()){
						trollEnvoye=item;
					}
					items.add(item);
				}

				if(trollEnvoye.getId()==0){
					//Le cas des ajouts de trolls
					trollEnvoye=items.get(items.size()-1);
				}
				editTrollWithRace((Troll)trollEnvoye);//affichage de la zone d'édition
				getContent().SetServeurInfo("Sauvegarde réussie");
			}
		};
		RemoveTrollcallback= new AsyncCallback<ArrayList<Troll>>() {

			@Override
			public void onFailure(Throwable caught) {
				RootPanel.get().add(new HTML("oups : " + caught.toString()));
				// Show the RPC error message to the user
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(SERVER_ERROR);
				System.out.println("--FAILURE");
			}

			@Override
			public void onSuccess(ArrayList<Troll> trolls) {
				items = new ArrayList<Item>();
				for (Troll item : trolls) {
					items.add(item);
				}
				//editTrollWithRace((Troll)getContent().getItemEnCour());
				showContent(items);
				System.out.println("--SUCESS");
			}
		};

		// Effectuer l'appel au service
		myServiceTroll.getRaces(Racecallback);
		//myServiceTroll.getTrolls(Trollcallback);
	}
	public void showContent(ArrayList<Item> items){
		if(content.isAttached()){
			dockpanel.remove(content);

		}
		boolean showcontent = true;
		switch (numPage) {
		
		case 1:
			content = new ViewRaceChoice(items);												
			break;
		case 2:
			content = new ViewTrollEdit(items);							
			break;
		case 3:
			content = new ViewItemList(items,ViewItemList.LIST_TEXT);		
			break;
		case 4:
			content = new ViewItemList(items,ViewItemList.LIST_TABLEAU_IMG);	
			break;

		default:
			showcontent = false;
			break;
		}
		if (showcontent){
			dockpanel.add(content,DockPanel.CENTER);
		}
	}
	public void ChoiceTrollRace(Troll troll){
		if(content.isAttached()){
			dockpanel.remove(content);
		}
		content = new ViewRaceChoice(listeRaces,troll);												
		dockpanel.add(content,DockPanel.CENTER);
	}
	public void editTrollWithRace(Troll troll) {
		if(content.isAttached()){
			dockpanel.remove(content);
		}
		if(troll.getId()==0){
		content = new ViewTrollEdit(troll);
		}else{
		content = new ViewTrollEdit(items,troll);
		}
		dockpanel.add(content,DockPanel.CENTER);
	}
	public void showItemList(int typeAffichage, int triedBy) {
		if(content.isAttached()){
			dockpanel.remove(content);
		}
		content = new ViewItemList(items,typeAffichage,triedBy);		
		dockpanel.add(content,DockPanel.CENTER);
	}
	public static LaTerreDesTrolls get(){
		return SINGLETON;
	}
	public Content getContent(){
		return content;
	}
	public void retourAccueil() {
		MenuTroll m = (MenuTroll)menu.getWidget(0);
        m.getActiveItem().setStyleName("gwt-MenuItem");
        m.getItem(0).setStyleName("gwt-MenuItem-active");
        numPage = 1;
        myServiceTroll.getRaces(Racecallback);
		// TODO Auto-generated method stub
		
	}


	
}
